package com.suixinsanren.design.observer.demo01;

import java.util.ArrayList;
import java.util.List;

public class WeatherData implements Subject {

    private Double temperature;
    private Double humidity;
    private Double pressure;
    private List<Observer> observers;
    private Boolean isChanged;

    public WeatherData() {
        this.observers = new ArrayList<>();
        isChanged = false;
    }

    public void update(Double temperature, Double humidity, Double pressure) {
        this.temperature = temperature;
        this.humidity = humidity;
        this.pressure = pressure;
        isChanged();
        notifyAllObserver();
    }

    @Override
    public void addObserver(Observer observer) {
        observers.add(observer);
    }

    @Override
    public void deleteObserver(Observer observer) {
        observers.remove(observer);
    }

    @Override
    public void notifyAllObserver() {
        if(isChanged){
            observers.forEach(item -> item.update(this.temperature, this.humidity, this.pressure));
            isChanged = false;
        }
    }

    @Override
    public void isChanged() {
        isChanged = true;
    }
}
